﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Core;
using Lion.WeiXin.Core.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Lion.WeiXin.Tools.Log;
namespace Lion.WeiXin.Controllers
{
    [PermissionFilter]
    public class CmsMenuController : Controller
    {

        ICmsMenu imenu = new CmsMenuDAO();

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string title, int currentPage, int pageSize)
        {
            //数据量少的，直接查全部数据分页展示           
            List<CmsMenuModel> list = imenu.GetList(string.Empty);
            int totalCount = list.Count;
            //如果传入条件参数
            title = HttpUtility.UrlDecode(title);
            if (!string.IsNullOrEmpty(title))
            {
                list = list.Where(n => n.Title.Contains(title)).OrderBy(n => n.Code).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                list = list.OrderBy(n => n.Code).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }

        public ActionResult Show()
        {
            string ID = Request.QueryString["ID"];
            if (string.IsNullOrEmpty(ID))
            {
                return Redirect(Request.RawUrl);
            }
            CmsMenuModel model = imenu.GetModel(int.Parse(ID));
            return View(model);
        }

        public ActionResult Create()
        {
            string pcode = Request.QueryString["ParentCode"];
            List<CmsMenuModel> list = imenu.GetList(string.Empty);

            string newCode = GetNewCode(pcode, list);
            ViewBag.Code = newCode;
            ViewBag.ParentCode = pcode;
            return View();
        }

        public string GetNewCode(string parentCode, List<CmsMenuModel> list)
        {
            string result = string.Empty;
            //当前菜单是否为一级菜单，3位一级
            if (parentCode == "000" && parentCode.Length == 3)
            {
                //查询所有一级节点
                List<CmsMenuModel> topDics = list.Where(n => n.Code.Length == 3).ToList();
                if (topDics.Count == 0)
                {
                    //数据库中无一条记录,所有子节点从100开始
                    result = "100";
                }
                else
                {
                    long maxKey = topDics.Max(n => long.Parse(n.Code));
                    result = (maxKey + 1).ToString();
                }
            }
            else
            {
                //查找当前节点的所有子节点，子节点的长度是父节点长度+3，并且子节点包含父节点
                List<CmsMenuModel> childDics = list.Where(n => n.Code.IndexOf(parentCode) == 0 && n.Code.Length== parentCode.Length+3).ToList();
                if (childDics.Count == 0)
                {
                    //无子节点 
                    result = parentCode + "001";
                }
                else
                {
                    long maxKey = childDics.Max(n => long.Parse(n.Code));
                    result = (maxKey + 1).ToString();
                }
            }

            return result;
        }


        public ActionResult Save(FormCollection form)
        {
            string action = Request.QueryString["Action"];
            string result = string.Empty;

            CmsMenuModel model = new CmsMenuModel();
            TryUpdateModel(model);
            result = SaveStateEnum.OK.ToString();
            try
            {
                if (action == ActionEnum.Create.ToString())
                {
                    imenu.Add(model);
                }
                else if (action == ActionEnum.Update.ToString())
                {
                    imenu.Update(model);
                }
                else
                {
                    result = SaveStateEnum.NO.ToString();
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据{0}失败", action);
                result = SaveStateEnum.NO.ToString();
            }

            return Content(result);
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    imenu.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }
    }
}
